package com.shuziren.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuziren.abnormal.CustomException;
import com.shuziren.domain.CandidateEntity;
import com.shuziren.domain.InterPersonEntity;
import com.shuziren.domain.dto.CandidateUpdateDto;
import com.shuziren.entity.InterviewPosition;
import com.shuziren.mapper.CandidateMapper;
import com.shuziren.pojo.dto.InterviewScheduleDto;
import com.shuziren.pojo.entity.InterviewSchedule;
import com.shuziren.mapper.InterviewScheduleMapper;
import com.shuziren.pojo.entity.vo.InterviewScheduleVo;
import com.shuziren.pojo.vo.InterviewScheduleVVo;
import com.shuziren.service.CandidateService;
import com.shuziren.service.InterPersonService;
import com.shuziren.service.InterviewPositionService;
import com.shuziren.service.InterviewScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class InterviewScheduleServiceImpl extends ServiceImpl<InterviewScheduleMapper, InterviewScheduleVo> implements InterviewScheduleService {

    @Autowired
    private InterviewScheduleMapper interviewScheduleMapper;

    @Autowired
    private CandidateService candidateService;

    @Autowired
    private InterviewPositionService interviewPositionService;

    @Autowired
    private InterPersonService interPersonService;

    @Override
    public InterviewScheduleVo getInterviewScheduleById(Integer id) throws CustomException {
        if (id == null || id == 0) {
            throw new CustomException("面试安排ID为空或无效");
        }
        InterviewScheduleVo interviewScheduleVo = interviewScheduleMapper.selectById(id);
        if (interviewScheduleVo == null) {
            throw new CustomException("未找到ID为 " + id + " 的面试安排");
        }
        return interviewScheduleVo;
    }

    @Override
    public boolean addInterviewSchedule(InterviewSchedule interviewSchedule) throws CustomException {
        if (interviewSchedule == null) {
            throw new CustomException("面试安排对象为空");
        }
        List<Integer> questionset = interviewSchedule.getQuestionset();
        if (questionset == null || questionset.isEmpty()) {
            throw new CustomException("问题集为空");
        }
        JSONArray array = JSONUtil.parseArray(questionset);
        InterviewScheduleVo vo = interviewSchedule.toVo();
        if (vo == null) {
            throw new CustomException("转换为InterviewScheduleVo失败");
        }
        vo.setQuestionset(array);
        int insert = interviewScheduleMapper.insert(vo);
        if (insert <= 0) {
            throw new CustomException("插入面试安排失败");
        }
        return true;
    }

    @Override
    public boolean updateInterviewSchedule(InterviewSchedule interviewSchedule) throws CustomException {
        if (interviewSchedule == null) {
            throw new CustomException("面试安排对象为空");
        }
        List<Integer> questionset = interviewSchedule.getQuestionset();

        JSONArray array = JSONUtil.parseArray(questionset);
        InterviewScheduleVo vo = interviewSchedule.toVo();
        if (vo == null) {
            throw new CustomException("转换为InterviewScheduleVo失败");
        }
        vo.setQuestionset(array);
        int update = interviewScheduleMapper.updateById(vo);
        if (update == 0) {
            throw new CustomException("更新面试安排失败");
        }
        return true;
    }

    @Override
    public Page<InterviewScheduleVVo> getAllInterviewSchedulePage(InterviewScheduleDto interviewSchedule) throws CustomException {
        if (interviewSchedule == null) {
            throw new CustomException("查询条件对象为空");
        }
        Page<InterviewScheduleVo> page = new Page<>(interviewSchedule.getPageNum(), interviewSchedule.getPageSize());
        QueryWrapper<InterviewScheduleVo> queryWrapper = new QueryWrapper<>();

        // 判断是否需要全量查询
        boolean fullQuery = (interviewSchedule.getCandidateId() == null || interviewSchedule.getCandidateId() == 0) 
            && (interviewSchedule.getPositionId() == null || interviewSchedule.getPositionId() == 0)
            && (interviewSchedule.getDigitalInterviewerId() == null || interviewSchedule.getDigitalInterviewerId() == 0);

        if (!fullQuery) {
            if (interviewSchedule.getCandidateId() != null && interviewSchedule.getCandidateId() != 0) {
                queryWrapper.eq("candidate_id", interviewSchedule.getCandidateId());
            }
            if (interviewSchedule.getPositionId() != null && interviewSchedule.getPositionId() != 0) {
                queryWrapper.eq("position_id", interviewSchedule.getPositionId());
            }
            if (interviewSchedule.getDigitalInterviewerId() != null && interviewSchedule.getDigitalInterviewerId() != 0) {
                queryWrapper.eq("digital_interviewer_id", interviewSchedule.getDigitalInterviewerId());
            }
        }

        Page<InterviewScheduleVo> interviewScheduleVoPage = interviewScheduleMapper.selectPage(page, queryWrapper);
        List<InterviewScheduleVVo> interviewScheduleVVos = new ArrayList<>();
        List<InterviewScheduleVo> records = interviewScheduleVoPage.getRecords();

        records.forEach(interviewScheduleVo -> {
            InterviewScheduleVVo vvo = new InterviewScheduleVVo();
            vvo.setId(interviewScheduleVo.getId());
            vvo.setCandidateId(interviewScheduleVo.getCandidateId());
            vvo.setPositionId(interviewScheduleVo.getPositionId());
            vvo.setInterviewTime(interviewScheduleVo.getInterviewTime());
            vvo.setDuration(interviewScheduleVo.getDuration());
            vvo.setDigitalInterviewerId(interviewScheduleVo.getDigitalInterviewerId());
            vvo.setNotes(interviewScheduleVo.getNotes());
            vvo.setStatus(interviewScheduleVo.getStatus());
            vvo.setCreatedAt(interviewScheduleVo.getCreatedAt());
            vvo.setUpdatedAt(interviewScheduleVo.getUpdatedAt());
            vvo.setQuestionset(interviewScheduleVo.getQuestionset());
            vvo.setTemporaryPasswords(interviewScheduleVo.getTemporaryPasswords());


            // 查询候选人姓名
            CandidateEntity candidate = candidateService.getById(interviewScheduleVo.getCandidateId());
            if (candidate != null) {
                vvo.setCandidateName(candidate.getName());
            }
            if (candidate != null){
                vvo.setCandidatePhone(candidate.getPhone());
            }

            // 查询职位名称
            InterviewPosition position = interviewPositionService.getInterviewPosition(interviewScheduleVo.getPositionId());
            if (position != null) {
                vvo.setPositionName(position.getPositionName());
            }

            InterPersonEntity interperson = interPersonService.getById(interviewScheduleVo.getDigitalInterviewerId());
            if (interperson != null) {
                vvo.setDigitalInterviewerName(interperson.getName());
            }

            interviewScheduleVVos.add(vvo);
        });

        Page<InterviewScheduleVVo> interviewScheduleVVOPage = new Page<>();
        interviewScheduleVVOPage.setCurrent(page.getCurrent());
        interviewScheduleVVOPage.setSize(page.getSize());
        interviewScheduleVVOPage.setTotal(page.getTotal());
        interviewScheduleVVOPage.setRecords(interviewScheduleVVos);
        return interviewScheduleVVOPage;
    }

}